'use strict';
// 1.引入模块
let
    router = require('koa-router')(),
    fs = require('fs'),
    path = require('path');



function searchRouter(dir) {
    let
        files = fs.readdirSync(dir),
        routerFile = files.filter(file => {
            return file.endsWith('.js') && file !== 'index.js'
        });
    return routerFile
}

// 3.使用循环进行遍历我们的路由文件
function registerRouter(files, dir) {
    files.forEach(item => {
        // 需要引入所有路由文件
        let tmpFile = path.join(dir, item);
        let tmpRouter = require(tmpFile);
        for (let i in tmpRouter) {
            let
                type = tmpRouter[i][0],
                fn = tmpRouter[i][1];
            if (type === 'get') {
                router.get(i, fn)
            } else if (type === 'post') {
                router.post(i, fn)
            }
        }
    });
}

// 4.暴露模块 最后需要返回启动路由 这样就注册所有的路由成功了
module.exports = function() {
    let dir = __dirname;
    let files = searchRouter(dir);
    registerRouter(files, dir);
    return router.routes();
};